/*
 * @lc app=leetcode.cn id=107 lang=cpp
 *
 * [107] 二叉树的层次遍历 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> ans;
        queue<TreeNode*> que[2];
        int flag = 0;
        que[flag].push(root);

        vector<int> tmp;
        while (!que[flag].empty())
        {
            TreeNode* p = que[flag].front();
            que[flag].pop();
            if(p != NULL){
                tmp.push_back(p->val);
                que[(flag + 1) % 2].push(p->left);
                que[(flag + 1) % 2].push(p->right);
            }
            if(que[flag].empty())
            {
                if(!tmp.empty())
                    ans.insert(ans.begin(), tmp);
                tmp.clear();
                flag = (flag + 1) % 2;
            }
        }
        
        return ans;
    }

    
};
// @lc code=end

